import pandas as pd
import json
import matplotlib.pyplot as plt
from PIL import Image
import sqlite3
import time
from threading import Thread
from txttopic import merge_images, add_text_to_image
from const import *


def check_status(station=1):
    print(f"\033[33m生成{station}运行状态...\033[0m")
    now = int(time.time())
    if station == 1:
        conn = sqlite3.connect(db1_path)
        running_list = []
        running_time = 0
        for i in range(4):
            df = pd.read_sql_query(
                f"SELECT * FROM dianyadianliu WHERE ename='{i+1}' and time<={now} ORDER BY time desc LIMIT 1",
                conn)
            if not df.empty:
                if df["lcU"][0] and df["LcI"][0]:
                    df['tmptime'] = pd.to_datetime(df['time'],
                                                   unit='s',
                                                   utc=True)  # 这里假设时间戳是以秒为单位
                    df['tmptime'] = df['tmptime'].dt.tz_convert(
                        'Asia/Shanghai')  # 然后转换到上海时区（或你需要的时区）
                    # 然后你可以使用strftime方法格式化时间
                    df['formatted_time'] = df['tmptime'].dt.strftime(
                        '%y-%m-%d %H:%M:%S')
                    # print(df['ename'][0], df['formatted_time'][0], df['Ia'][0],
                    #       df['Ib'][0], df['Ic'][0])
                    running_list.append(df['ename'][0] + '#')
                    running_time = df['formatted_time'][0]
        conn.close()
        return running_list, running_time

    elif station == 2:
        conn = sqlite3.connect(db2_path)
        # cursor = conn.cursor()
        running_list = []
        running_time = 0
        for i in range(4):
            df = pd.read_sql_query(
                f"SELECT * FROM dydlpqcos WHERE name='{i+1}' and time<={now} ORDER BY time desc LIMIT 1",
                conn)
            if not df.empty:
                if df["Ia"][0] and df["Ic"][0]:
                    df['tmptime'] = pd.to_datetime(df['time'],
                                                   unit='s',
                                                   utc=True)  # 这里假设时间戳是以秒为单位
                    df['tmptime'] = df['tmptime'].dt.tz_convert(
                        'Asia/Shanghai')  # 然后转换到上海时区（或你需要的时区）
                    # 然后你可以使用strftime方法格式化时间
                    df['formatted_time'] = df['tmptime'].dt.strftime(
                        '%y-%m-%d %H:%M:%S')
                    # print(df['name'][0], df['formatted_time'][0], df['Ia'][0],
                    #       df['Ib'][0], df['Ic'][0])
                    running_list.append(df['name'][0] + '#')
                    running_time = df['formatted_time'][0]
        conn.close()
        return running_list, running_time


def get_main_image(station_name: str,
                   station=1,
                   font_size=20,
                   font_color=(255, 255, 255),
                   background_color=(0, 0, 0)):
    '''
    获取主界面图像
    :return:
    '''
    station_part_name = '#'
    station_part_list, station_running_time = check_status(station)
    if station_part_list:
        station_status = '正在运行'
        station_part_name = ' '.join(station_part_list)
        background_color = (0, 0, 205)
    else:
        station_status = '无机组运行'
        station_running_time = time.strftime('%y-%m-%d %H:%M:%S',
                                             time.localtime())
        background_color = (0, 0, 0)
    th_list = []
    # 生成站实时报表
    if station == 1:
        # th_list.append(Thread(target=getgq_1zhan_image))
        with open('./data/check.json', 'r') as f:
            j = json.load(f)
            j[station] = 1
        with open('./data/check.json', 'w') as f:
            json.dump(j, f)
    elif station == 2:
        # th_list.append(Thread(target=getgq_2zhan_image))
        with open('./data/check.json', 'r') as f:
            j = json.load(f)
            j[station] = 1
        with open('./data/check.json', 'w') as f:
            json.dump(j, f)
    # # 生成上位机是否在线状态
    # th_list.append(
    #     Thread(target=copy_file,
    #            args=('./image/com_run.png',
    #                  f'./image/{station}_zhan_status.png')))
    # 生成温度
    th_list.append(Thread(target=getwd_zhan_image, args=(station - 1, )))
    # 生成总览
    th_list.append(
        Thread(
            target=add_text_to_image,
            kwargs={
                'output_path':
                f'./image/{station}_station_main_image.png',
                'text_list': [
                    station_name, station_status, station_part_name,
                    station_running_time
                ],
                # x=20,
                # y=20,
                'font_path':
                './font/Yahei.TTF',  # 替换为实际字体文件路径
                'font_size':
                font_size,
                'font_color':
                font_color,  # 白色文字
                'background_color':
                background_color  # 黑色文字
            }))
    for th in th_list:
        th.daemon = True
        th.start()
    for th in th_list:
        th.join()


def getwd_zhan_image(num):
    '''
    获取机组温度数据，并绘制图像
    :param num: 机组编号0代表1站，1代表2站
    :return:
    '''
    # 创建一个包含8个进程的进程池
    # pool = Pool(processes=8)
    now = time.time()
    # th_list = []
    result = None
    if int(num) == 0:
        members_list1 = [
            "time", "t_U2", "t_U3", "t_V3", "t_W1", "t_W2", "t_W3"
        ]
        members_list2 = [
            "time", "t_Z5", "t_Z6", "t_Z7", "t_Z9", "t_X1", "t_X2", "t_Z10",
            "t_Z11", "t_syg", "t_xyg"
        ]
        members_name1 = [
            "时间", "定子U相2", "定子U相3", "定子V相3", "定子W相1", "定子W相2", "定子W相3"
        ]
        members_name2 = [
            "时间", "推力轴Z5", "推力轴Z6", "推力轴Z7", "推力轴Z9", "上导X1", "上导X2", "下导Z10",
            "下导Z11", "上油缸", "下油缸"
        ]
        filename1 = '1_th1'
        filename2 = '2_th1'
        members_list = [members_list1, members_list2]
        members_name = [members_name1, members_name2]
        filename_list = [filename1, filename2]
        title_list = ['定子', '导瓦&油缸']
        # # 使用pool多进程
        # for i in range(4):
        #     for index, member in enumerate(members_list):
        #         pool.apply_async(save_wd_1zhan_image,
        #                          args=(i, member, members_name[index],
        #                                title_list[index], filename_list[index],
        #                                24))
        # # 关闭进程池，不再接受新任务
        # pool.close()
        # # 等待所有进程执行完毕
        # pool.join()
        # 使用多线程
        th_list = []
        for i in range(4):
            for index, member in enumerate(members_list):
                th = Thread(target=save_wd_1zhan_image,
                            args=(i, member, members_name[index],
                                  title_list[index], filename_list[index], 24))
                th_list.append(th)
        # 供水
        members_list = ['time', 'mgwd', 'cswd1', 'cswd2', 'cswd3']
        members_name = ['时间', '母管温度', '出水温度1', '出水温度2', '出水温度3']
        th = Thread(target=save_qtwd_1zhan_image,
                    args=(members_list, members_name, 'gongshui', '冷水机组', 24))
        th_list.append(th)
        # 变压器温度
        members_list = [
            'time', 'zbwd', 'sbA', 'sbB', 'sbC', 'sbD', 'zbA', 'zbB', 'zbC',
            'zbD'
        ]
        members_name = [
            '时间',
            '主变温度',
            '所变温度A',
            '所变温度B',
            '所变温度C',
            '所变温度D',
            '站变温度A',
            '站变温度B',
            '站变温度C',
            '站变温度D',
        ]
        th = Thread(target=save_qtwd_1zhan_image,
                    args=(members_list, members_name, 'byqwd', '变压器', 24))

        th_list.append(th)
        for th in th_list:
            th.daemon = True
            th.start()
        for th in th_list:
            th.join()
        print(time.time() - now)
        image_list = []
        image_list.append(Image.open(f'./image/#1_gongshui.png'))
        image_list.append(Image.open(f'./image/#1_byqwd.png'))
        for i in range(4):
            for filename in filename_list:
                # with open(f'./image/#{i+1}_th.png', 'rb') as f:
                image_list.append(Image.open(f'./image/#{i+1}_{filename}.png'))
            # image_list.append(Image.open(f'./image/#{i+1}_{filename2}.png'))
        if image_list:
            result = merge_images(image_list, f'./image/#1zwd_th.png', 1)
        return result
    elif int(num) == 1:
        members_list1 = [
            'time', 'dz1', 'dz2', 'dz3', 'dz4', 'dz5', 'dz6', 'dz7', 'dz8',
            'dz9'
        ]
        members_name1 = [
            "时间", "定子1", "定子2", "定子3", "定子4", "定子5", "定子6", "定子7", "定子8", "定子9"
        ]
        members_list2 = [
            'time', 'tlw1', 'tlw2', 'tlw3', 'tlw4', 'tlw5', 'syg', 'xdw', 'xyg'
        ]
        members_name2 = [
            "时间", "推力瓦1", "推力瓦2", "推力瓦3", "推力瓦4", "推力瓦5", "上油缸", "下导瓦", "下油缸"
        ]
        members_list3 = ['time', 'lc1', 'lc2', 'lc3']
        members_name3 = ["时间", "励磁1", "励磁2", "励磁3"]
        filename1 = '1_th2'
        filename2 = '2_th2'
        filename3 = '3_th2'
        members_list = [members_list1, members_list2, members_list3]
        members_name = [members_name1, members_name2, members_name3]
        filename_list = [filename1, filename2, filename3]
        title_list = ['定子', '导瓦&油缸', '励磁']
        # 使用多线程
        th_list = []
        for i in range(4):
            for index, member in enumerate(members_list):
                th = Thread(target=save_wd_2zhan_image,
                            args=(i, member, members_name[index],
                                  title_list[index], filename_list[index], 24))
                th_list.append(th)
        for th in th_list:
            th.daemon = True
            th.start()
        for th in th_list:
            th.join()
        # for i in range(4):
        #     for index, member in enumerate(members_list):
        #         pool.apply_async(save_wd_2zhan_image,
        #                          args=(i, member, members_name[index],
        #                                title_list[index], filename_list[index],
        #                                24))
        # # 关闭进程池，不再接受新任务
        # pool.close()
        # # 等待所有进程执行完毕
        # pool.join()
        image_list = []
        for i in range(4):
            for filename in filename_list:
                image_list.append(Image.open(f'./image/#{i+1}_{filename}.png'))
            # image_list.append(Image.open(f'./image/#{i+1}_{filename2}.png'))
            # image_list.append(Image.open(f'./image/#{i+1}_{filename3}.png'))
        if image_list:
            result = merge_images(image_list, f'./image/#2zwd_th.png', 1)
        print(time.time() - now)
        return result


def save_wd_1zhan_image(num,
                        members_list: list,
                        members_name: list,
                        title_flag='',
                        filename='#',
                        timerange=12):
    '''
    保存一站温度趋势的图片
    :param num: 机组编号
    :param members_list: 机组代号列表
    :param members_name: 机组名称列表
    :param title_flag: 标题标识
    :param filename: 文件名标识
    :param timerange: 时间范围默认12小时内
    :return:
    '''
    conn = sqlite3.connect(db1_path)
    # c = conn.cursor()
    now_time = int(time.time())
    begin_time = int(time.time() - timerange * 60 * 60)
    # print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(begin_time)),
    #       time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time)))
    # df_list = []
    # print(now_time)
    # sqltxt = f'''SELECT "time", "ename", "t_U2", "t_U3", "t_V3", "t_W1", "t_W2", "t_W3", "t_Z5", "t_Z6", "t_Z7", "t_Z9", "t_X1", "t_X2", "t_Z10", "t_Z11", "t_syg", "t_xyg" FROM wendu WHERE time BETWEEN {start_time} AND {now_time} ORDER BY time DESC LIMIT 1'''
    # for i in range(num):
    sqltxt = f'''SELECT {",".join(members_list)} FROM wendu WHERE "ename"={num+1} AND  "time" BETWEEN {begin_time} AND {now_time} ORDER BY time'''
    df = pd.read_sql_query(sqltxt, conn)
    conn.close()
    # df_list.append(df)
    fig, ax = plt.subplots(figsize=(4, 6))
    # xlims = ax.get_xlim()
    # print(xlims)
    # 确保 df['time'] 是 datetime 类型，如果不是则需要转换
    # print(df["time"])
    if not isinstance(df['time'].dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
        # df['time'] = pd.to_datetime(df['time'], unit='s')
        df['time'] = pd.to_datetime(df['time'], unit='s',
                                    utc=True)  # 先转换为UTC的datetime
        df['time'] = df['time'].dt.tz_convert(
            'Asia/Shanghai')  # 然后转换到上海时区（或你需要的时区）
    try:
        start_time = df['time'].iloc[0]
        end_time = df['time'].iloc[-1]
        # print(start_time, end_time)
        for index, member in enumerate(members_list[1:]):
            # 获取特定列的最大值和最小值
            max_value = df[member].max()
            max_index = df[member].idxmax()
            max_time = df['time'].iloc[max_index]
            min_value = df[member].min()
            min_index = df[member].idxmin()
            min_time = df['time'].iloc[min_index]

            line, = ax.plot(df['time'], df[member])
            curve_color = line.get_color()  # 获取曲线的颜色
            # ax.annotate(
            #     text=f"{members_name[index]}",
            #     xy=(start_time, df[member].iloc[0]),
            #     xycoords='data',
            #     xytext=(start_time - pd.Timedelta(minutes=5),
            #             df[member].iloc[0]),
            #     textcoords='data',
            #     rotation=45,
            #     fontsize=5,
            #     color=curve_color,
            # )
            cur_value = df[member].iloc[-1]
            ax.annotate(
                text=f"{members_name[index+1]} {cur_value:.1f}℃",
                xy=(end_time, cur_value),
                xycoords='data',
                xytext=(end_time + pd.Timedelta(hours=1), cur_value),
                rotation=45,
                textcoords='data',
                fontsize=9,
                color=curve_color,
                # arrowprops=dict(facecolor='blue')
            )
            # time_text = max_time.strftime('%Y-%m-%d %H:%M:%S').replace(
            #     ' ', '\n')
            ax.annotate(text=f"Max:{max_value:.1f}℃",
                        xy=(max_time, max_value),
                        xycoords='data',
                        xytext=(max_time, max_value + 0.0),
                        textcoords='data',
                        fontsize=9,
                        color=curve_color,
                        arrowprops=dict(facecolor=curve_color))
            # time_text = min_time.strftime('%Y-%m-%d %H:%M:%S').replace(
            #     ' ', '\n')
            # ax.annotate(text=f"Min:{min_value:.1f}℃\n{time_text}\n",
            #             xy=(min_time, min_value),
            #             xycoords='data',
            #             xytext=(min_time, min_value + 0.0),
            #             rotation=45,
            #             textcoords='data',
            #             fontsize=5,
            #             color='green',
            #             arrowprops=dict(facecolor='green'))
            # ax.plot(df['time'], df[member])

        # 手动指定图例项
        # plt.legend(['曲线1', '曲线2'])
        plt.xticks(rotation=45)
        ax.set_title(f"{num+1}#机组{timerange}小时{title_flag}温度趋势")
        # ax.set_xlabel('时间')
        ax.legend(members_name[1:])
        # 调整子图间距和图表边缘空白
        # left, bottom, right, top 分别表示图表区左侧、底部、右侧、顶部边缘距离图形窗口边缘的比例
        # wspace 和 hspace 分别是宽度和高度方向上的子图间距
        fig.subplots_adjust(
            # left=0.1,
            bottom=0.1,
            right=0.8,
            top=0.95,
            # wspace=0.2,
            # hspace=0.2
        )
        fig.savefig(f'./image/#{num+1}_{filename}.png', dpi=80)
        plt.close(fig)  # 关闭图形以释放资源
    except Exception as e:
        print(e)


    # conn.close()
def save_wd_2zhan_image(num,
                        members_list: list,
                        members_name: list,
                        title_flag='',
                        filename='#',
                        timerange=12):
    '''
    保存二站温度趋势的图片
    :param num: 机组编号
    :param members_list: 机组代号列表
    :param members_name: 机组名称列表
    :param title_flag: 标题标识
    :param filename: 文件名标识
    :param timerange: 时间范围默认12小时内
    :return:
    '''
    # members_list = [
    #     'time', 'tlw1', 'tlw2', 'tlw3', 'tlw4', 'tlw5', 'syg', 'xdw', 'xyg',
    #     'dz1', 'dz2', 'dz3', 'dz4', 'dz5', 'dz6', 'dz7', 'dz8', 'dz9', 'lc1',
    #     'lc2', 'lc3'
    # ]
    # members_name = [
    #     "时间", "推力瓦1", "推力瓦2", "推力瓦3", "推力瓦4", "推力瓦5", "上油缸", "下导瓦", "下油缸",
    #     "定子1", "定子2", "定子3", "定子4", "定子5", "定子6", "定子7", "定子8", "定子9", "励磁1",
    #     "励磁2", "励磁3"
    # ]
    conn = sqlite3.connect(db2_path)
    # c = conn.cursor()
    now_time = int(time.time())
    begin_time = int(time.time() - timerange * 60 * 60)
    # print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(begin_time)),
    #       time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time)))
    # df_list = []
    # print(now_time)
    # sqltxt = f'''SELECT "time", "ename", "t_U2", "t_U3", "t_V3", "t_W1", "t_W2", "t_W3", "t_Z5", "t_Z6", "t_Z7", "t_Z9", "t_X1", "t_X2", "t_Z10", "t_Z11", "t_syg", "t_xyg" FROM wendu WHERE time BETWEEN {start_time} AND {now_time} ORDER BY time DESC LIMIT 1'''
    # for i in range(num):
    sqltxt = f'''SELECT {",".join(members_list)} FROM wd WHERE "name"={num+1} AND  "time" BETWEEN {begin_time} AND {now_time} ORDER BY time'''
    df = pd.read_sql_query(sqltxt, conn)
    # df_list.append(df)
    fig, ax = plt.subplots(figsize=(4, 6))
    # xlims = ax.get_xlim()
    # print(xlims)
    # 确保 df['time'] 是 datetime 类型，如果不是则需要转换
    # print(df["time"])
    if not isinstance(df['time'].dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
        # df['time'] = pd.to_datetime(df['time'], unit='s')
        df['time'] = pd.to_datetime(df['time'], unit='s',
                                    utc=True)  # 先转换为UTC的datetime
        df['time'] = df['time'].dt.tz_convert(
            'Asia/Shanghai')  # 然后转换到上海时区（或你需要的时区）
    start_time = df['time'].iloc[0]
    end_time = df['time'].iloc[-1]
    # print(start_time, end_time)
    for index, member in enumerate(members_list[1:]):
        # 获取特定列的最大值和最小值
        max_value = df[member].max()
        max_index = df[member].idxmax()
        max_time = df['time'].iloc[max_index]
        min_value = df[member].min()
        min_index = df[member].idxmin()
        min_time = df['time'].iloc[min_index]

        line, = ax.plot(df['time'], df[member])
        curve_color = line.get_color()  # 获取曲线的颜色
        # ax.annotate(
        #     text=f"{members_name[index]}",
        #     xy=(start_time, df[member].iloc[0]),
        #     xycoords='data',
        #     xytext=(start_time - pd.Timedelta(minutes=5),
        #             df[member].iloc[0]),
        #     textcoords='data',
        #     rotation=45,
        #     fontsize=5,
        #     color=curve_color,
        # )
        cur_value = df[member].iloc[-1]
        ax.annotate(
            text=f"{members_name[index+1]} {cur_value:.1f}℃",
            xy=(end_time, cur_value),
            xycoords='data',
            xytext=(end_time + pd.Timedelta(hours=1), cur_value),
            rotation=45,
            textcoords='data',
            fontsize=9,
            color=curve_color,
            # arrowprops=dict(facecolor='blue')
        )
        # time_text = max_time.strftime('%Y-%m-%d %H:%M:%S').replace(
        #     ' ', '\n')
        ax.annotate(text=f"Max:{max_value:.1f}℃",
                    xy=(max_time, max_value),
                    xycoords='data',
                    xytext=(max_time, max_value + 0.0),
                    textcoords='data',
                    fontsize=9,
                    color=curve_color,
                    arrowprops=dict(facecolor=curve_color))
        # time_text = min_time.strftime('%Y-%m-%d %H:%M:%S').replace(
        #     ' ', '\n')
        # ax.annotate(text=f"Min:{min_value:.1f}℃\n{time_text}\n",
        #             xy=(min_time, min_value),
        #             xycoords='data',
        #             xytext=(min_time, min_value + 0.0),
        #             rotation=45,
        #             textcoords='data',
        #             fontsize=5,
        #             color='green',
        #             arrowprops=dict(facecolor='green'))
        # ax.plot(df['time'], df[member])

    # 手动指定图例项
    # plt.legend(['曲线1', '曲线2'])
    plt.xticks(rotation=60)
    ax.set_title(f"{num+1}#机组{timerange}小时{title_flag}温度趋势")
    # ax.set_xlabel('时间')
    ax.legend(members_name[1:])
    # 调整子图间距和图表边缘空白
    # left, bottom, right, top 分别表示图表区左侧、底部、右侧、顶部边缘距离图形窗口边缘的比例
    # wspace 和 hspace 分别是宽度和高度方向上的子图间距
    fig.subplots_adjust(
        # left=0.1,
        bottom=0.1,
        right=0.8,
        top=0.95,
        # wspace=0.2,
        # hspace=0.2
    )
    fig.savefig(f'./image/#{num+1}_{filename}.png', dpi=80)
    plt.close(fig)  # 关闭图形以释放资源
    conn.close()


def save_qtwd_1zhan_image(members_list,
                          members_name,
                          table_name,
                          image_name,
                          timerange=12):
    '''
    获取变压器、供水温度参数的图片
    param: members_list: 需要获取的数据库列名列表
            members_name: 参数中文名列表
            table_name: 数据库表名
            image_name: 图片名
            timerange: 获取数据的时间范围，单位为小时
    return: 返回给小程序用的图片
    '''
    now_time = int(time.time())
    begin_time = int(time.time() - timerange * 60 * 60)
    conn = sqlite3.connect(db1_path)
    df = pd.read_sql_query(
        f"SELECT {','.join(members_list)} FROM {table_name} WHERE time BETWEEN {begin_time} AND {now_time} ORDER BY id",
        conn)
    conn.close()
    # print(df)
    fig, ax = plt.subplots(figsize=(4, 6))
    if not isinstance(df['time'].dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
        df['time'] = pd.to_datetime(df['time'], unit='s',
                                    utc=True)  # 先转换为UTC的datetime
        df['time'] = df['time'].dt.tz_convert(
            'Asia/Shanghai')  # 然后转换到上海时区（或你需要的时区）
    start_time = df['time'].iloc[0]
    end_time = df['time'].iloc[-1]

    for index, member in enumerate(members_list[1:]):
        # 获取特定列的最大值和最小值
        max_value = df[member].max()
        max_index = df[member].idxmax()
        max_time = df['time'].iloc[max_index]
        min_value = df[member].min()
        min_index = df[member].idxmin()
        min_time = df['time'].iloc[min_index]
        line, = ax.plot(df['time'], df[member])
        curve_color = line.get_color()  # 获取曲线的颜色
        cur_value = df[member].iloc[-1]
        ax.annotate(
            text=f"{members_name[index+1]} {cur_value:.1f}℃",
            xy=(end_time, cur_value),
            xycoords='data',
            xytext=(end_time + pd.Timedelta(hours=1), cur_value),
            rotation=45,
            textcoords='data',
            fontsize=9,
            color=curve_color,
            # arrowprops=dict(facecolor='blue')
        )
        ax.annotate(text=f"Max:{max_value:.1f}℃",
                    xy=(max_time, max_value),
                    xycoords='data',
                    xytext=(max_time, max_value + 0.0),
                    textcoords='data',
                    fontsize=9,
                    color=curve_color,
                    arrowprops=dict(facecolor=curve_color))
    # 手动指定图例项
    # plt.legend(['曲线1', '曲线2'])
    plt.xticks(rotation=45)
    ax.set_title(f"{image_name}{timerange}小时温度趋势")
    # ax.set_xlabel('时间')
    ax.legend(members_name[1:])
    # 调整子图间距和图表边缘空白
    # left, bottom, right, top 分别表示图表区左侧、底部、右侧、顶部边缘距离图形窗口边缘的比例
    # wspace 和 hspace 分别是宽度和高度方向上的子图间距
    fig.subplots_adjust(
        # left=0.1,
        bottom=0.1,
        right=0.8,
        top=0.95,
        # wspace=0.2,
        # hspace=0.2
    )
    fig.savefig(f'./image/#1_{table_name}.png', dpi=80)
    plt.close(fig)  # 关闭图形以释放资源


if __name__ == '__main__':
    get_main_image("抽水站")
    # check_status()
